package com.itchu.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itchu.auth.config.JwtProperties;
import com.itchu.common.domain.Payload;
import com.itchu.common.exption.ExceptionEnum;
import com.itchu.common.exption.MusicException;
import com.itchu.common.utils.CookieUtils;
import com.itchu.common.utils.JwtUtils;
import com.itchu.system.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 登出成功处理逻辑
 */
@Component
public class CustomizeLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private JwtProperties prop;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 1.从cookie获取token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getAuthCookieName());
        // 2.验证token是否合法
        Payload<SysUser> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), SysUser.class);
        } catch (Exception e) {
            throw new MusicException(ExceptionEnum.MUSIC_INVALID_UNAUTHRIZED);
        }

        // 3.判断过期时间是否大于10s,是就存就redis里面（作用是当作黑名单处理）
        Date exTime = payload.getExpiration();
        long remainTime = exTime.getTime() - System.currentTimeMillis();
        if (remainTime > 10000) {
            redisTemplate.opsForValue().set(payload.getId(),"1",remainTime, TimeUnit.MILLISECONDS);
        }
        // 4.删除cookie
        CookieUtils.deleteCookie(prop.getUser().getAuthCookieName(),prop.getUser().getCookieDomain(),response);

        try {
            //登录成功時，返回json格式进行提示
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            PrintWriter out = response.getWriter();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("code", HttpServletResponse.SC_OK);
            map.put("message", "退出成功");
            out.write(new ObjectMapper().writeValueAsString(map));
            out.flush();
            out.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}